package com.mjfeed.controller.shop.member;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Comment;
import com.mjfeed.entity.Member;
import com.mjfeed.entity.Order;
import com.mjfeed.entity.Product;
import com.mjfeed.service.CommentService;
import com.mjfeed.service.MemberService;
import com.mjfeed.service.OrderService;
import com.mjfeed.service.ProductService;

/**
 * @description 评价
 * @author zhaominglei
 * @date 2014年12月28日
 */
@Controller("shopCommentController")
@RequestMapping("/member/comment")
public class CommentController extends BaseController {
	@Resource(name="memberService")
	private MemberService memberService;
	@Resource(name="orderService")
	private OrderService orderService;
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="commentService")
	private CommentService commentService;
	
	@RequestMapping(value = "/add", method=RequestMethod.GET)
	public String add(Long orderId, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("order", orderService.getById(Order.class, orderId));
		return "shop/member/comment/add";
	}
	
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	public String save(HttpServletRequest request, HttpServletResponse response, Model model){
		Member member = memberService.getCurrent();
		if (member == null || member.getId() == null || member.getId() < 1) {
			return ERROR_VIEW;
		}
		Long orderId = Long.valueOf(request.getParameter("orderId"));
		Long productId = Long.valueOf(request.getParameter("productId"));
		Integer score = Integer.valueOf(request.getParameter("score"));
		String content = request.getParameter("content");
		if (orderId == null || orderId.intValue() < 1
				|| productId == null || productId.intValue() < 1
				|| score == null || score < 1
				|| content == null || content.equals("")) {
			return ERROR_VIEW;
		}
		Order order = orderService.getById(Order.class, orderId);
		Product product = productService.getById(Product.class, productId);
		if (order == null || product == null) {
			return ERROR_VIEW;
		}
		Comment comment = new Comment();
		comment.setOrder(order);
		comment.setProduct(product);
		comment.setMember(member);
		comment.setScore(score);
		comment.setContent(content);
		comment.setIsShow(true);
		comment.setIp(super.getRemoteIpAddr(request));
		commentService.save(comment);
		
		request.setAttribute("order", order);
		return "redirect:/member/comment/add.shtml?orderId="+orderId;
	}
}
